package com.demo.cms.webapp.template.directive;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.springframework.util.Assert;

import com.demo.Constants;
import com.demo.core.model.Site;
import com.demo.webapp.context.MultisiteContextHolder;
import com.demo.webapp.views.freemarker.directive.core.PageContextDirectiveSupport;

import freemarker.core.Environment;
import freemarker.core.Environment.TemplateDirectiveBodyEx;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * 评论页面自定义指令
 * @author ryuu.kk
 *
 */
public class CommentPageDirective extends PageContextDirectiveSupport {

	/**
	 * 页面模板名
	 */
	private static final String COMMENT_PAGE_TEMPLATE_NAME = "classpath:/com/demo/cms/webapp/template/commentPage.ftl";
	
	/**
	 * 是否允许评论
	 */
	private boolean isAllow;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void preWriter(Environment env, TemplateDirectiveBodyEx bodyEx,
			TemplateModel[] loopVars, SimpleHash hash, Map params)
			throws IOException, TemplateException {
		
		isAllow = true;
		
		// 评论的文章id
		Long id;
		// 评论ID
		Long commentId;
		// 评论&反馈类型：1评论; 2反馈
		String type;
		// 允许匿名评论
		boolean isAnonymous = false;
		//SimpleNumber
		id = getLong("articleId", params);
		commentId = getLong("commentId", params);
		type = getString("type", params, getDefaultValue("type"));
		
		// 评论列表页地址
		String commentUrl = queryUrl(hash, params);
		
		// 是否支持匿名评论
		HttpRequestHashModel requestModel = (HttpRequestHashModel) hash.get(FreemarkerManager.KEY_REQUEST);
		HttpServletRequest request = requestModel.getRequest(); 
		// 获得基础参数
		Map<String, Object> configMap = (Map<String, Object>) request.getSession().getServletContext().getAttribute(com.demo.webapp.config.Constants.CONFIG);
		// 分离当前站点的配置参数
		Site site = MultisiteContextHolder.getSite();
		if (site == null) {
			throw new IllegalArgumentException("Not found site in " + getClass());
		}
		String domain = site.getDomain();
		Map<String, Object> siteConfig = (Map<String, Object>) configMap.get(domain);
		if (siteConfig != null) {
			Boolean isAllow = (Boolean) configMap.get(Constants.ARTICLE_REPLY_ANONYMOUS); 
			isAnonymous = isAllow == null ? false : isAllow.booleanValue();
		}
		// 是否允许匿名访问
		hash.put("allowAnonymous", isAnonymous);
		
		hash.put("commentUrl", commentUrl);
		hash.put("commentId", commentId);
		hash.put("type", type);
		hash.put("articleId", id);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String getTemplatePath(Map params) {
		String path = "";
		// 判断是否允许评论
		if (isAllow) {
			// 只有允许才可以创建评论
			try {
				path = getString("path", params, COMMENT_PAGE_TEMPLATE_NAME);
			} catch (TemplateModelException e) {}
		}
		return path;
	}
	
	@Override
	public void afterInvoke(Writer writer) {
		
	}
	
	@SuppressWarnings("rawtypes")
	private String queryUrl(SimpleHash hash, Map params) {
		String value = "";
		String url = "";
//		Long id = null;
		HttpServletRequest request = null;;
		HttpServletResponse response = null;
		try {
			HttpRequestHashModel requestModel = (HttpRequestHashModel) hash.get(FreemarkerManager.KEY_REQUEST);
			response = requestModel.getResponse();
			request = requestModel.getRequest();
			value = getString("commentUrl", params, getDefaultValue("commentUrl"));
			
//			id = getLong("id", params);
//			
//			if (id != null && value.indexOf("?") > 0) {
//				value += "&id=" + id;
//			} else {
//				value += "?id=" + id;
//			}
			if (value.startsWith("/")) {
				value = request.getContextPath() + value;
			}
			url = response.encodeURL(value);
		} catch (TemplateModelException e) {
			e.printStackTrace();
		}
		//hash.put("page", page);
		return url;
	}
}
